<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="商户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="merchantId">
              <j-dict-select-tag
                v-model="model.merchantId"
                dict-code="HC_MERCHANT,STORE_NAME,ID,DEL_FLAG=0"
                placeholder="请选择商户"
                @change="merchantChange"
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="商品图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productPicture">
              <j-image-upload v-model="model.productPicture" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="商品图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productPicture">
              <div @click="showImgCropper" class="pointer">{{ model.productPicture ? '更换图片' : '选择图片' }}</div>
              <img
                style="max-width: 300px"
                @click="showImgCropper"
                :src="model.productPicture"
                v-if="model.productPicture"
                alt=""
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="商品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tradeName">
              <a-input v-model="model.tradeName" placeholder="请输入商品名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="商品描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.productDescription" placeholder="请输入商品描述"></a-input>
            </a-form-model-item>
          </a-col>

          <!--  v-if="merchant.customPriceFlag"  -->
          <a-col :span="24">
            <a-form-model-item label="商品价格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="commodityPrice">
              <a-radio-group
                v-model="model.commodityPrice"
                button-style="solid"
                v-if="merchant.customPriceFlag != '是'"
              >
                <a-radio-button
                  :value="String(merchant.storeUnitPrice[index])"
                  @click="storeUnitPriceClick(merchant.storeUnitPrice[index])"
                  v-for="(item, index) in merchant.storeUnitPrice"
                  :key="index"
                >
                  {{ merchant.storeUnitPrice[index] }}
                </a-radio-button>
              </a-radio-group>
              <a-input-number
                v-else
                v-model="model.commodityPrice"
                :min="0"
                :precision="2"
                placeholder="请输入商品价格"
                style="width: 130px; margin-left: 10px"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="规格"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="commoditySpecifications"
            >
              <div class="title spec">
                <a-checkbox @change="onChange" v-model="model.specificationsFlag"> 启用规格</a-checkbox>
                <a-button type="primary" @click="addFirstSpec">添加一级规格</a-button>
              </div>
              <div class="specContent">
                <div v-for="(item, index) in model.commoditySpecifications" :key="index">
                  <div class="specList">
                    <div class="">
                      <a-input type="text" v-model="item.name" :clearable="false" placeholder="一级规格名称"></a-input>
                    </div>
                    <div class="">
                      <a-button type="primary" icon="plus" style="margin-left: 5px" @click="addSecoundSpec(index)" />
                      <a-button type="danger" icon="minus" style="margin-left: 5px" @click="delFirstSpec(index)" />
                    </div>
                  </div>
                  <template v-if="item.child && item.child.length != 0">
                    <div class="specList secound" v-for="(childItem, childIndex) in item.child" :key="childIndex">
                      <div class="">
                        <div class="">
                          <a-input type="text" :clearable="false" v-model="childItem.name" placeholder="二级规格名称">
                          </a-input>
                        </div>
                        <div class="">
                          <a-input-number
                            v-if="model.commodityPrice === '' || model.commodityPrice === null"
                            type="text"
                            :clearable="false"
                            v-model="childItem.price"
                            placeholder="价格"
                          >
                          </a-input-number>
                        </div>
                      </div>
                      <div class="">
                        <a-button
                          type="danger"
                          icon="minus"
                          style="margin-left: 5px"
                          @click="delSecoundSpec(index, childIndex)"
                        />
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="限购" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="limitBuy">
              <a-input-number
                :min="-1"
                :precision="0"
                v-model="model.limitBuy"
                placeholder="请输入限购,-1表示不限数量"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-model="model.sort" placeholder="请输入排序" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="是否上架" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="upFlag">
              <a-radio-group v-model="model.upFlag" button-style="solid">
                <a-radio-button value="上架中">上架中</a-radio-button>
                <a-radio-button value="下架中">下架中</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="是否必选" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="requiredFlag">
              <a-radio-group v-model="model.requiredFlag" button-style="solid">
                <a-radio-button value="是">是</a-radio-button>
                <a-radio-button value="否">否</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <ImgCropper ref="imgCropper" @getImgSrc="getImgSrc"></ImgCropper>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import ImgCropper from './imgCropper.vue'

export default {
  name: 'HcCommodityForm',
  components: { ImgCropper },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {
        upFlag: '上架中',
        requiredFlag: '否',
        limitBuy: '-1',
        specificationsFlag: false,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        merchantId: [{ required: true, message: '请选择商户' }],
        tradeName: [{ required: true, message: '请输入商品名称!' }],
        // commodityPrice: [{ required: true, message: '请输入商品价格!' }],
        // productPicture: [{ required: true, message: '请输入商品图片!' }],
        limitBuy: [{ required: true, message: '请输入限购!' }],
        sort: [{ required: true, message: '请输入排序!' }],
        upFlag: [{ required: true, message: '请选择是否上架!' }],
        // requiredFlag: [{ required: true, message: '请选择是否必选!' }],
      },
      url: {
        add: '/hc/hcCommodity/add',
        edit: '/hc/hcCommodity/edit',
        queryById: '/hc/hcCommodity/queryById',
      },
      merchant: {},
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    console.log('this.model', this.model)
  },
  methods: {
    //展示图片裁剪弹窗
    showImgCropper() {
      this.$refs.imgCropper.show()
    },
    //图片裁剪上传后的回调
    getImgSrc(value) {
      this.model.productPicture = value
      this.$forceUpdate()
    },

    storeUnitPriceClick(val) {
      if (this.model.commodityPrice == val) {
        this.model.commodityPrice = null
      }
    },
    //选择商家之后获取对应的商家信息
    merchantChange(val) {
      this.hcMerchantQueryById(val)
    },
    //获取对应的商家信息
    hcMerchantQueryById(val) {
      getAction('/hc/hcMerchant/queryById', { id: val }).then((res) => {
        let that = this
        if (res.success) {
          that.merchant = res.result
          that.merchant.storeUnitPrice = that.merchant.storeUnitPrice ? JSON.parse(that.merchant.storeUnitPrice) : ''
          console.log('that.merchant', that.merchant)
        }
      })
    },
    add() {
      this.edit(this.modelDefault, 'add')
    },
    edit(record, type) {
      this.model = Object.assign({}, record)
      if (type != 'add') {
        this.model.specificationsFlag = this.model.specificationsFlag == '是' ? true : false
        this.model.commoditySpecifications = JSON.parse(this.model.commoditySpecifications)
        console.log('this.model.commodityPrice', this.model.commodityPrice)
        this.model.commodityPrice =
          this.model.commodityPrice !== null && this.model.commodityPrice !== ''
            ? String(this.model.commodityPrice)
            : ''
      }

      if (this.model.merchantId) {
        this.hcMerchantQueryById(this.model.merchantId)
      }

      this.visible = true
    },
    //添加一级规格
    addFirstSpec() {
      if (this.model.commoditySpecifications) {
        let flag = false
        this.model.commoditySpecifications.forEach((item) => {
          if (!item.name) {
            this.$message.warning('请填写一级规格名称')
            flag = true
          } else {
            item.child.forEach((childItem) => {
              if (!childItem.name) {
                this.$message.warning('请填写二级规格名称')
                flag = true
              }
            })
          }
        })
        if (flag) {
          return
        }
        this.$set(this.model.commoditySpecifications, this.model.commoditySpecifications.length, {
          name: '',
          child: [
            {
              name: '',
              price: '',
            },
          ],
        })
      } else {
        this.$set(this.model, 'commoditySpecifications', [{ name: '', child: [{ name: '', price: '' }] }])
      }
    },
    //添加二级规格
    addSecoundSpec(index) {
      let flag = false
      this.model.commoditySpecifications.forEach((item) => {
        console.log('item', item)
        if (!item.name) {
          this.$message.warning('请先填写对应的一级规格名称')
          flag = true
        }
      })
      if (flag) {
        return
      }
      this.model.commoditySpecifications[index].child.push({
        name: '',
        price: '',
      })
    },
    //删除一级规格
    delFirstSpec(index) {
      this.model.commoditySpecifications.splice(index, 1)
    },
    //删除二级规格
    delSecoundSpec(index, childIndex) {
      this.model.commoditySpecifications[index].child.splice(childIndex, 1)
    },
    //是否启用规格单选框值更改时触发
    onChange(e) {
      this.model.specificationsFlag = e.target.checked
    },
    submitForm() {
      // if (!this.model.specificationsFlag) {
      //   this.model.specificationsFlag = false
      // }
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          // if (this.model.commodityPrice == 0) {
          //   this.$message.warning('商品价格不能为0')
          //   return
          // }
          if (
            this.model.commodityPrice &&
            String(this.model.commodityPrice).split('.').length != 1 &&
            String(this.model.commodityPrice).split('.')[1].length > 2
          ) {
            this.$message.warning('自定义价格只能是两位小数')
            return
          }
          if (!this.model.productPicture) {
            this.$message.warning('请上传商品图片')
            return
          }

          let flag = false

          if (this.model.specificationsFlag) {
            if (!this.model.commoditySpecifications || this.model.commoditySpecifications.length == 0) {
              this.$message.warning('请填写规格')
              return
            }
          }

          // if (!this.model.commodityPrice) {
          if (!this.model.commodityPrice&&this.model.commodityPrice!==0) {
            if (!this.model.commoditySpecifications || this.model.commoditySpecifications.length == 0) {
              this.$message.warning('请填写价格或启用规格')
              return
            }

            let count = 0
            this.model.commoditySpecifications.forEach((item) => {
              if (!item.name) {
                this.$message.warning('请填写一级规格名称')
                flag = true
              } else {
                item.child.forEach((childItem) => {
                  if (!childItem.name) {
                    this.$message.warning('请填写二级规格名称')
                    flag = true
                  }
                  if (!childItem.price || childItem.price == 0) {
                    count++
                  }
                })
              }
            })
            if (count >= this.model.commoditySpecifications.length) {
              this.$message.warning('不能所有一级规格的二级规格里面都存在不填价格和价格为0的情况')
              return
            }
          }
          if (flag) {
            return
          }

          // if (!this.model.commodityPrice) {
          if (this.model.commodityPrice === null || this.model.commodityPrice === '') {
            if (this.model.commoditySpecifications) {
              if (this.model.commoditySpecifications.length == 0) {
                this.$message.warning('由于您没有选择和填写价格，请填写规格')
                return
              }
              if (!this.model.specificationsFlag) {
                this.$message.warning('请填写价格或者启用规格')
                return
              }
            } else {
              this.$message.warning('请填写价格或者启用规格')
              return
            }
          }

          let obj = JSON.parse(JSON.stringify(this.model))
          obj.specificationsFlag = obj.specificationsFlag ? '是' : '否'
          obj.commoditySpecifications = JSON.stringify(this.model.commoditySpecifications)

          that.confirmLoading = true
          let httpurl = ''
          let method = ''


          if (!this.model.id) {
            console.log('我在新增')
            httpurl += this.url.add
            method = 'post'
          } else {
            console.log('我在复制')
            httpurl += this.url.edit
            method = 'post'
          }
          httpAction(httpurl, obj, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@mixin flex($transverse: flex-start, $portrait: center) {
  display: flex;
  @if ($transverse) {
    justify-content: $transverse;
  }
  @if ($transverse) {
    align-items: $portrait;
  }
}

.specList {
  @include flex(space-between, center);

  ::v-deep .ant-input-number {
    margin-bottom: 0;
  }

  div {
    @include flex();
    margin-bottom: 10px;

    &:nth-child(2) {
      margin-left: 10px;
    }
  }

  img {
    cursor: pointer;
  }

  .add {
    width: 20px;
    height: 20px;
    margin-left: 10px;
  }

  .del {
    width: 25px;
    height: 25px;
    margin-left: 10px;
  }
}

.secound {
  margin-left: 20px;

  > div {
    > div:nth-child(2) {
      width: 70px;
    }
  }
}

.spec {
  @include flex(space-between, center);

  > div {
    @include flex();
    color: #f1b825;
    cursor: pointer;
  }
}

.pointer {
  cursor: pointer;
}
</style>